#!/usr/bin/env python
# -*- coding: utf8 -*-
# title       :
# description :
# author      :'ShenMeng'

from PySide import QtCore, QtGui
from .movewidget import MoveWidget
from .noborderwidget import NoBorderWidget
import images2gif
from PIL import Image, ImageGrab
import time
# from io import BytesIO
import os
class GifScreenGrabber(NoBorderWidget):
    def __init__(self, parent=None):
        """
        Constructor
        """
        super(GifScreenGrabber, self).__init__(parent)
        self._stop = 1
        self._save = 0
        self._images = []
        self._show = 0
        self._number = 0
        self._speed = 0.1
        self._capture_rect = QtCore.QRect()
        self.setMinimumWidth(250)
        self.setMinimumHeight(100)
        self.setStyleSheet("""
                            *{
                                color:rgb(250,250,250);font: 9pt \"Arial\";
                                border:none;
                            }
                            QLineEdit{
                            border-radius:5px;
                            background-color:red;
                            }
                            """)
        ### tool bos ###
        # create
        self.tool_box = MoveWidget(self)
        self.tool_box.setMinimumWidth(300)
        space_label = QtGui.QLabel(' Time(s):')
        self.space_time = QtGui.QLineEdit()
        self.space_time.setFixedWidth(30)
        self.space_time.setFixedHeight(15)
        regx = QtCore.QRegExp("[0-9.]+")
        validator = QtGui.QRegExpValidator(regx, self.space_time)
        self.space_time.setValidator(validator)
        self.space_time.setText('0.1')
        self.space_time.setStyleSheet("border-radius:5px;background-color:rgba(0,0,0,100);")

        play_speed = QtGui.QLabel('  Speed:')
        self.play_speed = QtGui.QLineEdit()
        regx = QtCore.QRegExp("[0-9.]+")
        validator = QtGui.QRegExpValidator(regx, self.play_speed)
        self.play_speed.setValidator(validator)
        self.play_speed.setText('0.1')
        self.play_speed.setFixedWidth(30)
        self.play_speed.setFixedHeight(15)
        self.play_speed.setStyleSheet("border-radius:5px;background-color:rgba(0,0,0,100);")


        self.close_btn = QtGui.QToolButton()
        self.close_btn.setIcon(QtGui.QIcon(r'D:\develop\apps\local\smdesktop\resources\close_win.png'))
        self.close_btn.setAutoRaise(1)
        self.run_btn = QtGui.QPushButton()
        self.run_btn.setFlat(1)
        self.run_btn.setCheckable(True)
        self.run_btn.setChecked(0)
        self._play_icon = QtGui.QIcon(r'D:\develop\apps\local\validation\src\validation\resources\play_icon_black.png')
        self._stop_icon = QtGui.QIcon(r'D:\develop\apps\local\validation\src\validation\resources\stop_icon_black.png')
        self.run_btn.setIcon(self._play_icon)
        self.save_btn = QtGui.QToolButton()
        self.save_btn.setIcon(QtGui.QIcon(R'D:\develop\apps\local\validation\src\validation\resources\pause_icon_black.png'))
        self.save_btn.setAutoRaise(1)
        self.save_btn.setHidden(1)
        self.tip_info = QtGui.QLabel()
        self.tip_info.setFixedWidth(30)
        self.tip_info.setStyleSheet('color:red;')
        self.number_info = QtGui.QLabel(u'0 张')
        # layout
        self.tool_box.main_layout.addWidget(space_label)
        self.tool_box.main_layout.addWidget(self.space_time)
        self.tool_box.main_layout.addWidget(play_speed)
        self.tool_box.main_layout.addWidget(self.play_speed)
        self.tool_box.main_layout.addSpacing(5)
        self.tool_box.main_layout.addWidget(self.run_btn)
        self.tool_box.main_layout.addSpacing(5)
        self.tool_box.main_layout.addWidget(self.save_btn)
        self.tool_box.main_layout.addItem(QtGui.QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum))
        self.tool_box.main_layout.addWidget(self.number_info)

        self.tool_box.main_layout.addSpacing(5)
        self.tool_box.main_layout.addWidget(self.tip_info)
        self.tool_box.main_layout.addSpacing(5)
        self.tool_box.main_layout.addWidget(self.close_btn)
        # connect
        self.close_btn.clicked.connect(self.close)
        self.save_btn.clicked.connect(self.on_save_btn_clicked)
        self.run_btn.toggled.connect(self.on_run_btn_clicked)
        self.run_btn.enterEvent = self.run_pause_info
        self.run_btn.leaveEvent = self.run_pause_info
        self.save_btn.enterEvent = self.stop_info
        self.save_btn.leaveEvent = self.stop_info

    def on_save_btn_clicked(self):
        self._save = 1
        self.run_btn.setChecked(0)
        if self._show:
            self.grab_image()

    def closeEvent(self, event):
        self._stop = 0

    def stop_info(self, event):
        if event.type() == QtCore.QEvent.Type.Enter:
            self.tip_info.setText(u'停止')
        elif event.type() == QtCore.QEvent.Type.Leave:
            self.tip_info.setText('')

    def run_pause_info(self, event):
        if event.type() == QtCore.QEvent.Type.Enter:
            if self.run_btn.isChecked():
                self.tip_info.setText(u'暂停')
            else:
                self.tip_info.setText(u'抓取')
        elif event.type() == QtCore.QEvent.Type.Leave:
            self.tip_info.setText('')

    def get_grab_rect(self):
        top_left = self.mapToGlobal(self.rect().topLeft())
        bottom_right = self.mapToGlobal(self.rect().bottomRight())
        offset_height = self.tool_box.height()
        return [top_left.x()+1, top_left.y()+offset_height+2, bottom_right.x()-1, bottom_right.y()-1]

    def _save_gif(self):
        self._save = 0
        if not self._images:
            return
        try:
            # name_list = os.listdir(r'D:\develop\apps\tder\gifgrabber\src\gifgrabber\temp')
            # name_list.sort()
            # images = (Image.open('temp/%s' % name) for name in name_list if name.endswith('.png'))
            file_dialog = QtGui.QFileDialog()
            result_path = file_dialog.getSaveFileName(self, 'Save Image','', 'Image Files (*.gif)')[0]

            if not result_path:
                return
            images2gif.writeGif(result_path, self._images, duration=float(self._speed), nq=0.1)
        except ValueError, e:
            print e
        self._show = 0
        self.save_btn.setHidden(1)
        self.tip_info.setText('')
        self._number = 0
        self._images = []
        self.close()

    def on_run_btn_clicked(self, arg):
        self.tip_info.setText('')
        if arg:
            self.run_btn.setIcon(self._stop_icon)
            self._stop = 1
            if not self._show:
                self.save_btn.setHidden(0)
                self._show = 1
            self.grab_image()
        else:
            self.run_btn.setIcon(self._play_icon)
            self._stop = 0

    def grab_image(self):
        bbox = self.get_grab_rect()
        space_time = self.space_time.text()
        speed_value = self.play_speed.text()
        if not space_time or not speed_value:
            return
        self._speed = float(speed_value)
        while self._stop:
            QtGui.QApplication.instance().processEvents()
            time.sleep(float(space_time))
            img = ImageGrab.grab(bbox)
            self._images.append(img)
            # img.save('temp/grab%s.png' % self._number)
            self._number += 1
            self.number_info.setText(u'%s 张' % self._number)
        if self._save:
            print 'save..............'
            self._save_gif()

    def capture_rect(self):
        return self._capture_rect

    def paintEvent(self, event):
        super(GifScreenGrabber, self).paintEvent(event)
        painter = QtGui.QPainter(self)
        painter.setBrush(QtGui.QColor(255, 0, 0, 255))
        painter.setPen(QtCore.Qt.NoPen)
        painter.drawRect(self.rect())

        capture_rect = self.rect()#self.rect_area.rect()#
        painter.setCompositionMode(QtGui.QPainter.CompositionMode_Clear)
        painter.drawRect(capture_rect)

        painter.setCompositionMode(QtGui.QPainter.CompositionMode_SourceOver)
        pen = QtGui.QPen(QtGui.QColor(0, 120, 215, 255), 2, QtCore.Qt.SolidLine)
        painter.setPen(pen)
        # Draw cropping markers at click position
        # up
        painter.drawLine(event.rect().left(), event.rect().top()+self.tool_box.height()+1,
                         event.rect().right(), event.rect().top()+self.tool_box.height()+1)
        # down
        painter.drawLine(event.rect().left(), event.rect().bottom(),
                         event.rect().right(), event.rect().bottom())
        # left
        painter.drawLine(event.rect().left(), event.rect().top()+self.tool_box.height()+1,
                         event.rect().left(), event.rect().bottom())
        # left
        painter.drawLine(event.rect().right(), event.rect().top()+self.tool_box.height()+1,
                         event.rect().right(), event.rect().bottom())

    def showEvent(self, event):
        app = QtGui.QApplication.instance()
        app.installEventFilter(self)
        super(GifScreenGrabber, self).showEvent(event)


if __name__ == "__main__":
    app = QtGui.QApplication([])
    qw = GifScreenGrabber()
    qw.show()
    app.exec_()